package demo.socket;

import org.wevil.util.DateUtil;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * BIO多线程模型
 * */
public class BIOMThreadServer {
    public static void main(String[] args) throws IOException {
        // 1. 创建SocketServer端
        final ServerSocket socket = new ServerSocket(8900);
        while (true) {
            // 2. 等待客户端建立链接
            final Socket clientSocket = socket.accept();
            System.out.println("Accepted connection from " + clientSocket);
            // 3. 创建一个线程去处理客户端链接
            new Thread(new Runnable() {
                @Override
                public void run() {
                    OutputStream out;
                    try{
                        InputStream in = clientSocket.getInputStream();
                        // 4. 等待接收数据
                        System.out.println("等待接收数据：");
                        DataInputStream dis = new DataInputStream(in);
                        int len;
                        byte[] bytes = new byte[256];
                        String content = "";
                        while ((len = dis.read(bytes)) != -1) {
                            content = new String(bytes, 0, len);
                            System.out.println(DateUtil.getTimeStr() + " 接收数据：" + content);
                            // 暂停10秒，模拟服务端处理业务
                            Thread.sleep(1000*10);
                            // 读取完256个字节后就默认读取完成，跳出循环
                            break;
                        }
                        // 5. 回复数据
                        out = clientSocket.getOutputStream();
                        System.out.println(DateUtil.getTimeStr() + " 回复数据：Hi! " + content);
                        out.write("Hi!\r\n".getBytes(StandardCharsets.UTF_8));
                        out.flush();
                        // 6. 关闭链接
                        clientSocket.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
